import collections


class Solution(object):
    def isNStraightHand(self, hand, groupSize):
        n = len(hand)
        if n % groupSize != 0:
            return False
        c = collections.Counter(hand)
        pocket = [[key, c[key]] for key in c]
        pocket.sort()
        m = len(pocket)
        left = 0
        q = 0
        while left < m - groupSize + 1:
            if pocket[left][1] > 0:
                last_value = pocket[left][1]
                pocket[left][1] -= last_value
                q += last_value
                for right in range(left + 1, left + groupSize):
                    if pocket[right][0] == pocket[right - 1][0] + 1 and pocket[right][1] >= last_value:
                        pocket[right][1] -= last_value
                        q += last_value
                    else:
                        return False
            left += 1
        return q == n


data = Solution()
hand = [1, 2, 3, 6, 2, 3, 4, 7, 8]
groupSize = 3
print(data.isNStraightHand(hand, groupSize))
